<?php
namespace App\Repositories;

use App\Enums\RedisKeyEnum;
use App\Exceptions\BasicException;
use App\Response\Response;

class UserCommonWordsRepository
{
    //新增或编辑常用语
    public function addOrEdit($param)
    {
        $id = $param['id'] ?? 0;
        $content = $param['content'];
        $type = $param['type'];
        $sort = $param['sort'] ?? 1;
        $isDefault = $param['is_default'];

        $wordsId = app('model_user_common_words')
            ->where('content', $content)
            ->where(function ($query) use ($id) {
                if ($id > 0) {
                    $query->where('id', '<>', $id);
                }
            })->value('id');
        if ($wordsId) throw new BasicException(0, "常用语已经存在，序号{$wordsId}");

        $data = [
            'content' => $content,
            'type' => $type,
            'sort' => $sort,
            'is_default' => $isDefault,
        ];

        //最多添加3个默认常用语
        if ($isDefault == 1) {
            $defaultCommonWords = app('model_user_common_words')->where('is_default', 1);
        }

        if ($id > 0) {
            if ($isDefault == 1) {
                $defaultCommonWords = $defaultCommonWords->where('id', '<>', $id);
                if ($defaultCommonWords->count() >= 3) {
                    throw new BasicException(0, '最多只能设置3个默认常用语');
                }
            }

            $exist = app('model_user_common_words')->where('id', $id)->value('id');
            if (!$exist) throw new BasicException(0, 'id错误，记录不存在');

            $action = '编辑';
            $res = app('model_user_common_words')->where('id', $id)->update($data);

        } else {

            if ($isDefault == 1) {
                if ($defaultCommonWords->count() >= 3) {
                    throw new BasicException(0, '最多只能设置3个默认常用语');
                }
            }

            $action = '添加';
            $data['add_time'] = date('Y-m-d H:i:s');
            $res = app('model_user_common_words')->insertGetId($data);
        }

        if ($res) {
            //删除缓存
            app('redis')->del(sprintf(RedisKeyEnum::SYSTEM_COMMON_WORDS, $type));
            return Response::sendData([]);
        } else {
            throw new BasicException(0, $action.'失败');
        }
    }

}